package models

import (
	"fmt"
	"gin_template/core/setting"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"go.uber.org/zap"
)

var wConn *sqlx.DB // master for write
var rConn *sqlx.DB // slave for read

func InitDB() {
	var err error
	wdbConf := &setting.AppConf.MysqlConfig.Master
	rdbConf := &setting.AppConf.MysqlConfig.Slave

	fmt.Println("数据库配置", wdbConf)
	wDsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		wdbConf.User,
		wdbConf.Password,
		wdbConf.Ip,
		wdbConf.Port,
		wdbConf.Database)
	rDsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		rdbConf.User,
		rdbConf.Password,
		rdbConf.Ip,
		rdbConf.Port,
		rdbConf.Database)

	// 也可以使用MustConnect连接不成功就panic
	wConn, err = sqlx.Connect("mysql", wDsn)
	if err != nil {
		fmt.Printf("connect master DB failed, err:%v\n", err)
		return
	}
	wConn.SetMaxOpenConns(20)
	wConn.SetMaxIdleConns(10)

	rConn, err = sqlx.Connect("mysql", rDsn)
	if err != nil {
		fmt.Printf("connect slave DB failed, err:%v\n", err)
		return
	}
	rConn.SetMaxOpenConns(20)
	rConn.SetMaxIdleConns(10)

	fmt.Println("数据库连接成功")
	zap.L().Info("数据库连接成功")

	return
}
